package org.jeecg.modules.demo.test.controller;

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@ServerEndpoint("/xiajibaogaoim")
@Component
public class WebSocketServer {
    //静态变量，用来记录当前在线连接数。应该把他设计成线程安全的。
    private static AtomicInteger onlinenum = new AtomicInteger();

    //concurrent包的线程安全set，用来存放每个客户端对应的websicketserver对象
    private static ConcurrentHashMap<String, Session> sessionPools = new ConcurrentHashMap<>();

    //发送消息
    public void sendMessage(Session session,String message) {
        try {
            session.getBasicRemote().sendText(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //给制定用户发送消息
    public void sendInfo(String name,String message) {
        Session session = sessionPools.get(name);
        sendMessage(session,message);
    }

    //建立连接成功调用
    @OnOpen
    public void onOpen(Session session,String name){
        sessionPools.put(name,session);
        addOnlineCount();
        System.out.println(name + "加入webSocket！当前人数为" + onlinenum);
        sendMessage(session,"欢迎"+name+"加入聊天！");
    }

    //关闭链接时调用
    @OnClose
    public void onClose(String name){
        sessionPools.remove(name);
        subOnLineCount();
        System.out.println(name + "断开webSocket连接！当前人数为" + onlinenum);
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(String message){
        for (Session session: sessionPools.values()) {
            sendMessage(session,message);
        }
    }

    @OnError
    public void onError(Session session,Throwable throwable){
        System.out.println("发生错误");
        throwable.printStackTrace();
    }

    public static void addOnlineCount(){
        onlinenum.incrementAndGet();
    }

    public static void subOnLineCount(){
        onlinenum.decrementAndGet();
    }
}
